//获取项目根路径
function getRootPath() {
    var pathName = window.location.pathname.substring(1);
    var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
    return window.location.protocol + '//' + window.location.host + '/' + webName + '/';
}

var root = getRootPath();		// 全局根路径

//常用工具
var Tools = (function () {
    var preventDefault, panel, delay, panel0, toastPanel;
    return {
        getDate: function (type, dateParamter) {
            var date = dateParamter || new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;    //js从0开始取 
            if (month < 10) {
                month = "0" + month;
            }
            var day = date.getDate();
            if (day < 10) {
                day = "0" + day;
            }
            var hour = date.getHours();
            if (hour < 10) {
                hour = "0" + hour;
            }
            var minutes = date.getMinutes();
            if (minutes < 10) {
                minutes = "0" + minutes;
            }
            var second = date.getSeconds();
            if (second < 10) {
                second = "0" + second;
            }
            var dateStr = "";
            switch (type) {
                case 1:
                    dateStr = year + "年" + month + "月" + day + "日";
                    break;
                case 2:
                    dateStr = year + "年" + month + "月" + day + "日" + " " + hour + ":" + minutes + ":" + second;
                    break;
                case 3:
                    dateStr = year + "." + month + "." + day;
                    break;
                case 4:
                    dateStr = year + "." + month + "." + day + " " + hour + ":" + minutes + ":" + second;
                    break;
                case 5:
                    dateStr = year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + second;
                    break;
                case 6:
                    dateStr = year + "-" + month + "-" + day;
                    break;
                case 7:
                    dateStr = year + "/" + month + "/" + day + " " + hour + ":" + minutes + ":" + second;
                    break;
                case 8:
                    dateStr = year + "/" + month + "/" + day;
                    break;
                default:
                    dateStr = year + "-" + month + "-" + day + " " + hour + ":" + minutes;
                    break;
            }
            return dateStr;
        },
        // 获取窗口尺寸，包括滚动条
        getWindow: function () {
            return {
                width: window.innerWidth,
                height: window.innerHeight
            };
        },
        // 获取文档尺寸，不包括滚动条但是高度是文档的高度
        getDocument: function () {
            var doc = document.documentElement || document.body;
            return {
                width: doc.clientWidth,
                height: doc.clientHeight
            };
        },
        // 获取屏幕尺寸
        getScreen: function () {
            return {
                width: screen.width,
                height: screen.height
            };
        },
        // 显示、禁用滚动条
        showOrHideScrollBar: function (isShow) {
            preventDefault = preventDefault || function (e) {
                    e.preventDefault();
                };
            (document.documentElement || document.body).style.overflow = isShow ? 'auto'
                : 'hidden';
            // 手机浏览器中滚动条禁用取消默认touchmove事件
            if (isShow) {
                // 注意这里remove的事件必须和add的是同一个
                document
                    .removeEventListener('touchmove', preventDefault, false);
            } else {
                document.addEventListener('touchmove', preventDefault, false);
            }
        },
        addDate: function (date, numbers, type) {
            if (!date) {
                date = new Date();
            }
            if (!numbers) {
                numbers = 0;
            }
            var d = new Date(date);
            if (type == "year") {
                d.setFullYear(d.getFullYear() + numbers);
            } else if (type == "month") {
                d.setMonth(d.getMonth() + numbers);
            } else if (type == "day") {
                d.setDate(d.getDate() + numbers);
            } else if (type == "hours") {
                d.setHours(d.getHours() + numbers);
            } else if (type == "minute") {
                d.setMinutes(d.getMinutes() + numbers);
            } else if (type == "second") {
                d.setSeconds(d.getSeconds() + numbers);
            }
            var month = d.getMonth() + 1;
            var day = d.getDate();
            var hours = d.getHours();
            var minute = d.getMinutes();
            var second = d.getSeconds();
            if (month < 10) {
                month = "0" + month;
            }
            if (day < 10) {
                day = "0" + day;
            }
            if (hours < 10) {
                hours = "0" + hours;
            }
            if (minute < 10) {
                minute = "0" + minute;
            }
            if (second < 10) {
                second = "0" + second;
            }
            var val = d.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minute + ":" + second;
            return val;
        },
        DateNumber: function (startDate, endDate, type) {
            if (!startDate) {
                startDate = new Date();
            }
            if (!endDate) {
                endDate = new Date();
            }
            var d1 = new Date(startDate);
            var d2 = new Date(endDate);
            var d3 = d2.getTime() - d1.getTime();
            var result = "0";
            if (type == "year") {
                result = d2.getFullYear() - d1.getFullYear();
            } else if (type == "month") {
                result = (d2.getFullYear() - d1.getFullYear()) * 12 + (d2.getMonth() - d1.getMonth());
            } else if (type == "day") {
                result = Math.floor(d3 / (24 * 3600 * 1000));
            } else if (type == "hours") {
                //var leave1 = d3 % (24*3600*1000);    //计算天数后剩余的毫秒数
                result = Math.floor(d3 / (3600 * 1000));
            } else if (type == "minute") {
                //var leave2 = (d3 % (24*3600*1000)) % (3600*1000);        //计算小时数后剩余的毫秒数
                result = Math.floor(d3 / (60 * 1000));
            } else if (type == "second") {
                //var leave3 = ((d3 % (24*3600*1000)) % (3600*1000)) % (60*1000);      //计算分钟数后剩余的毫秒数
                result = Math.round(d3 / 1000);
            }
            return result;
        }
    };
})();

// 获取浏览器参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  // 匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; // 返回参数值
}
//去掉字符串两边的空格并去掉双引号，如:"    dd" aa  ",格式化后"dd aa";
function trimAndDelQuotation(str) {
    if (str == "") {
        return str;
    }
    var _temp = str.replace(/\"*/g, "");
    _temp = $.trim(_temp);
    return _temp;
}
//替换单引号问题
function replaceSingleQuote(str) {
    if (str == "") {
        return str;
    }
    var _temp = str.replace(/'/g, "\"");
    _temp = $.trim(_temp);
    return _temp;
}
$.views.converters("getSubStr", function (str, len) {
    if (str == undefined || str == null) {
        return "";
    }
    if (str.length > len) {
        return str.substr(0, len) + "...";
    }
    return str;
});

$.views.converters("pageSizeSelected", function (first, last) {
    if (first == null) return "";
    return first == last ? "selected=selected" : "";
});
//换行
$.views.converters("getLineStr", function (str, len) {
    if (str == undefined || str == null) {
        return "";
    }
    if (str.length > len) {
        var strs = '';
        for (var i = 0; i < str.length; i += len) {
            strs += str.substr(i, len) + '<br>';
        }
        return strs;
    }
    return str;
});
//以指定字符串结尾
String.prototype.endWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substring(this.length - s.length) == s)
        return true;
    else
        return false;
    return true;
};
//以指定字符串打头
String.prototype.startWith = function (s) {
    if (s == null || s == "" || this.length == 0 || s.length > this.length)
        return false;
    if (this.substr(0, s.length) == s)
        return true;
    else
        return false;
    return true;
};
Array.prototype.contains = function (item) {
    for (i = 0; i < this.length; i++) {
        if (this[i] == item) {
            return true;
        }
    }
    return false;
};
Array.prototype.remove = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i]
        }
    }
    this.length -= 1
};
/**
 * 自定义 confirm 项目中统一使用
 * @param msg    string/function
 * @param action function
 *
 * 依赖jquery-confirm；默认配置 http://craftpip.github.io/jquery-confirm/#options
 *
 * alerts, confirms and dialogs in one
 *
 * @author daundazhi
 * @time 2017-1-7
 */
jconfirm.defaults = {
    //常规主题设置
    theme: 'light', //http://craftpip.github.io/jquery-confirm/themes.html
    typeAnimated: true,
    animation: "zoom",
    closeAnimation: "scale",
    animationBounce: 1.2,
    animationSpeed: 500, // 0.5 seconds
    //标题icon
    icon: 'fa fa-warning',
    //右侧关闭按钮设置
    closeIcon: true,
    //整体位置设置
    //columnClass: 'col-md-4',//col-md-4 col-md-offset-8 col-xs-4 col-xs-offset-8
    //内容设置
    title: '确认!',
    defaultButtons: null,
    buttons: {
        warning: {
            text: '取消',
            btnClass: 'btn-default'
        }
    }
};
function myConfirm(msg, action) {
    return $.confirm({
        content: msg,
        buttons: {
            danger: {
                text: '确定',
                btnClass: 'btn-red any-other-class',
                action: action
            }
        }
    });
}
function myAlert(msg) {
    var jalert = $.alert({
        icon: null,
        title: null,
        content: msg,
        defaultButtons: null,
        buttons: {

            warning: {
                text: '取消',
                btnClass: 'btn-default'
            }
        }
    });
    return jalert;
}
/**
 *  自定义 laoding 项目中统一使用
 *  依赖 http://layer.layui.com/ 加载层 or loading层
 *
 * @author daundazhi
 * @time 2017-1-7
 */
function myLoading() {
    //风格1
    //加载层
    return layer.load(0, {shade: false}, {time: 60 * 1000}); //0代表加载的风格，支持0-2;并且设定最长等待60秒

    //风格2
    // return layer.msg('加载中', {
    //     icon: 16,
    //     shade: 0.01,
    //     time: 1000 * 60 * 2 //2秒关闭（如果不配置，默认是3秒）
    // });
}

/**
 * 添加加载框
 * @link http://stackoverflow.com/questions/1964839/how-can-i-create-a-please-wait-loading-animation-using-jquery
 */
var layerLoading;
$(document).on({
    ajaxStart: function () {
        layerLoading = myLoading();
    },
    ajaxStop: function () {
        layer.close(layerLoading);
        layer.closeAll();
        /**
         * 加载图片失败，怎样替换为默认图片
         * @link http://yongqing.is-programmer.com/posts/75280.html
         */
        $(document).ready(function () {
            // $("img").one("error", function (e) {
            //     var imgType = $(this).attr('imgType');
            //     var defaultImgSrc = $(this).attr('src');
            //     //$(this).attr("src", root + "/image/default.png");
            //     //有src有值，但是显示错误才进行处理
            //     if (!defaultImgSrc.toLowerCase().endWith("null")) {
            //         if (typeof(imgType) === 'undefined' || imgType === '') {
            //             $(this).attr("src", root + "/image/default.png");
            //         } else if (imgType == "1") {
            //             $(this).attr("src", root + "/image/default.png");
            //         }
            //     }
            // });
        });


        /**
         * 添加图片 layer ui photos
         * http://www.layui.com/doc/modules/layer.html#layer.photos
         *
         * demo
         // <div id="layer-photos-demo" class="layer-photos-demo">
         // <img layer-src="http://res.layui.com/images/fly/fly.jpg" layer-pid="" src="" alt="" layer-index="0">
         // <img layer-src="http://res.layui.com/images/fly/layim.jpg" layer-pid="" src="http://res.layui.com/images/fly/layim.jpg" alt="LayIM" layer-index="1">
         // <img layer-src="http://layer.layui.com/images/tong.jpg" layer-pid="" src="http://layer.layui.com/images/tong.jpg" alt="佟丽娅女神" layer-index="2">
         // <img layer-src="" layer-pid="" src="http://file.ynet.com/2/1603/09/10995825.jpg" alt="凤姐是个好人" layer-index="3">
         // <img layer-src="http://res.layui.com/images/sentsin/night.gif" layer-pid="" src="http://res.layui.com/images/sentsin/night.gif" alt="星空如此深邃" layer-index="4">
         // </div>
         */
        $(".layer-photos-demo").each(function () {
            var id = $(this).attr("id");
            //div ,p , td 标签都可以
            var photosObjectId = "#" + id;
            layer.photos({
                photos: photosObjectId
            });
        });
        layer.photos({
            photos: "#layer-photos-demo"
        });
    }
});
